<?php


namespace App\Http\Controllers\api\base;


use App\Common\statement\CommonStatement;
use App\Exceptions\api\BaseException;
use App\Models\config\Config;
use App\Models\fund\Coupon;
use App\Models\fund\Rebate;
use App\Models\fund\Recharge;
use App\Models\fund\Voucher;
use App\Models\goods\Order;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

trait ApiTrait
{

    public  function buyMemberSuccess(User $user,int $level,int $price)
    {


        $o['user_id'] = $user->id;
        $o['total_price'] = $price;
        $o['pay_money'] = $price;
        $o['money'] = $price;
        $o['old_price'] = $price;
        $o['remark'] = CommonStatement::level_text[$level];
        $o['coupon_money'] = 0;
        $o['ratio_money'] = 0;
        $o['detail'] = 0;
        $o['phone'] = 0;
        $o['order_no'] = 'buy_member';

        Order::create($o);

        $user->level = $level;
        $user->ratio = Config::getConfig("m{$level}-ratio");
        $user->save();

        if ($user->superior){
            if ($user->superior->level > 2){
                $money = bcmul($price,Config::getConfig('ms-ratio'),2);
                $user->superior->money += $money;
                $user->superior->save();

                $map['user_id'] = $user->superior->id;
                $map['relation_user_id'] = $user->id;
                $map['order_id'] = 0;
                $map['type'] = 2;

                $map['amount'] =  $money;
                $map['status'] = 1;
                $map['title']  = sprintf("用户%s购买会员奖励",$user->name);

                Rebate::create($map);
            }else{
                $map['amount'] = Config::getConfig('m-ratio');
                $map['title']  = sprintf("用户%s购买会员奖励",$user->name);
                //普通会员及以下等级推荐购买会员奖励优惠券金额满多少可用(元)
                $map['quota']  = Config::getConfig('member_quota');
                $map['end_at'] = Carbon::now()->addMonths(2);
                $map['status'] = 1;
                $map['user_id'] = $user->superior_id;
                Coupon::create($map);
            }
        }
        if ($level == 2 && Config::getConfig('buy_member1_money') > 1){
//            $item['amount'] = Config::getConfig('buy_member1_money');
//            $item['title'] = "购买普通会员赠送优惠券";
//            $item['quota'] = Config::getConfig('member_quota');
//            $item['end_at'] = Carbon::now()->addMonths(2);
//            $item['user_id'] = $user->id;
//            $item['status'] = 1;

            $item['user_id'] = $user->id;
            $item['code'] = $this->prefix.hashid($user->id).date('Ymd').'0';
            $item['title'] = Config::getConfig('buy_member1_title')??"购买普通会员赠送服务券";
            $item['amount'] = Config::getConfig('buy_member1_amount');
            $item['status'] = 1;
            $item['end_at'] = Carbon::now()->addDays(Config::getConfig('buy_member1_days')??60);


            $items[] = $item;
            $item['code'] .= 1;
            $items[] = $item;
            $item['code'] .= 2;
            $items[] = $item;
            Voucher::insert($items);
        }

    }

    /**
     * 添加充值记录
     * @param array $array
     * @return Recharge|\Illuminate\Database\Eloquent\Model
     * @throws BaseException
     */
    protected function addRechargeLog(array $array)
    {

        $fillable = [
            'user_id',
            'out_trade_no',
            'trade_no',
            'pay_money',
            'type',
        ];

        foreach ($fillable as $k => $v){
            if (isset($array[$v])){
                $params[$v] = $array[$v];
            }else{
                throw new BaseException(sprintf('func:addRechargeLog 缺失%s',$v));
            }
        }

        $params['title']    = $array['title'] ?? config('app.name').$array['pay_money'].'付款';
        $params['pay_type'] = $array['pay_type'] ?? $array['pay_type'] = 1;


        return Recharge::create($params);
    }



    /**
     * 添加资金记录
     * @param array $array
     * @param bool $pushJob
     * @return FundDetail|\Illuminate\Database\Eloquent\Model|\Illuminate\Foundation\Bus\PendingDispatch
     * @throws BaseException
     */
    protected function addFundDetailLog(array $array,$pushJob = false)
    {
        return addFundDetailLog($array,$pushJob);
        $fillable = [
            'user_id',
            'amount',
            'type',
            'money_type',
            'title',
            'status'
        ];

        foreach ($fillable as $k => $v){
            if (isset($array[$v])){
                $params[$v] = $array[$v];
            }else{
                throw new BaseException(sprintf('func:addFundDetailLog 缺失%s',$v));
            }
        }

        $params['title']    = $array['title'] ?? config('app.name').$array['pay_money'].'付款';

        if ($params['title'] == "0"){
            $params['title'] .= request()->url();
        }

        if ($pushJob){
            return FundDetailLog::dispatch($params);
        }else{
            return FundDetail::create($params);
        }

    }

    /**
     * 接口限流
     * @param int $sec 限流时间
     * @param int $id  指定用户
     * @param string $msg 提示信息
     * @throws BaseException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    protected function ApiLimit($sec = 1,$id = 0,$msg = '请求过于频繁,请稍后重试')
    {
        $key = request()->route()->getAction().$id;

        if (Cache::has('apiLimit'.$key)){
            throw new BaseException($msg);
        }
        Cache::set('apiLimit'.$key,true,Carbon::now()->addSeconds($sec));
    }


    /**
     * 销毁限流参数
     * @param int $id
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    protected function DestroyLimit($id = 0){
        $key = request()->route()->getAction().$id;
        Cache::delete('apiLimit'.$key);
    }


    public function orderCancel(Order $order)
    {

        $returnMoney = $order->money + $order->pay_money;

        if ($returnMoney > 0){

            User::whereId($order->user_id)->increment('money',$returnMoney);
        }

        if ($order->coupon_id > 0){
            $coupon = Coupon::find($order->coupon_id);
            if ($coupon){
                $coupon->status = 1;
            }
        }

    }

}